package com.uyii.springbootresilience4j;

import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import io.github.resilience4j.retry.annotation.Retry;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;


public class BackendAService {

    private final RestTemplate restTemplate;

    public BackendAService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @CircuitBreaker(name = "backendA", fallbackMethod = "fallback")
    @RateLimiter(name = "backendA")
    @Bulkhead(name = "backendA")
    @Retry(name = "backendA")
    @TimeLimiter(name = "backendA")
    public CompletableFuture<String> callExternalService() {
        return CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://external-service/api", String.class));
    }

    public String fallback(Throwable t) {
        return "External service is not available";
    }
}